# -*- coding:utf-8 -*-
# coding=utf-8
# 修改build文件

import sys
import importlib
import os
import codecs
import shutil
import random
import re
import json
import struct
import stat
from pathlib import Path

BUILD_FILE = "./uni_hb_m_solution/unione_lite_app_hb_m/build.sh"
NEW_BUILD_FILE = "./build.sh"
CUSTOM_JSON_FILE = "./uni_hb_m_solution/unione_lite_app_hb_m/tools/scripts/custom_config.json"
CLIENT_DIR = "./uni_hb_m_solution/unione_lite_app_hb_m/"
#BUILD_DIR = "./unione_lite_app_hb_m/"
OUTPUT_DIR = "../../output"
#复制后缀一样的文件到另一个目录
def copy_file(oldDir, newDir):
	#获取当前目录下的全部文件名 
	#拆分文件名 获取后缀一样的进行复制

	print("start to copy {0} to {1}".format(oldDir, newDir))
	
	#删除目录下所有文件
	print("del the old file")
	newfiles = os.listdir(newDir)
	for newfilename in newfiles:
		deldir = ""
		deldir += newDir
		deldir += "/"
		deldir += newfilename
		print(deldir)
		try:
			os.remove(deldir)
		except OSError as e:
			print("remove err {}\n".format(e))
	print("del all file")
	
	print("start copy file")
	#复制文件到新目录
	oldfiles = os.listdir(oldDir)
	for oldfilename in oldfiles:
		filename_split = oldfilename.split(".")	#oldfilename.split('.').pop(0)
		if len(filename_split) > 1:
			if filename_split[-1] == "xlsx" or filename_split[-1] == "json" or filename_split[-1] == "xls":
				oldCopyFile = ""
				newCopyFile = ""
				oldCopyFile += oldDir[2:]
				oldCopyFile += oldfilename
				newCopyFile += newDir
				newCopyFile += "/"
				newCopyFile += oldfilename
				print("copy {0} to {1}".format(oldCopyFile, newCopyFile))
				try:
					shutil.copyfile(oldCopyFile, newCopyFile)
					
				except:
					print("copy err")


#修改build 文件  增加编译后的输出路径
#输出格式 客户+产品+唤醒词+版本
def edit_build(oldFile, newFile, jsonFile):
	print("edit_build start\n")

	print("get the present dir\n")
	outputStr = ""
	dir = os.path.abspath(os.path.dirname(__file__))#获取文件夹名称
	dir_split = dir.split('\\')		#分割目录
	outputStr = dir_split[-2]		#获取本文件夹名称
	print(outputStr)

	outputStr += "_"
	outputListBuf = jsonFile["local"]["wakeup"]["keyword"][0]	#获取第一个唤醒词
	outputList = outputListBuf.replace(' ', '_')    #删除空格
	outputList += "_V"
	outputList += jsonFile["version"]						#获取官网的版本号
	print("get the wakeup work and verson")
	print(outputList)
	print("\n")

	outputStr += outputList
	print("show the new file name")
	print(outputStr)
	print("\n")
	
	#在sdk根目录增加一个客户文件夹 编译程序后 打包发客户
	clientDir = ""
	clientDir += CLIENT_DIR 
	clientDir += outputStr
	chectDir = Path(clientDir)
	if chectDir.is_dir() == False:#判断目录是否存在 不存在创建一个
		os.mkdir(clientDir)		#新建文件夹
		print(clientDir)
	else:
		#清空里面的内容
		print("dir is exist\n")
	copy_file("./", clientDir)#

	#加入打补丁指令
	# print("add patch to build \n")
	# newFile.write("patch -p1 < audio_play.patch"+ " \n"+ " \n")#bulid文件首行加入静音补丁

	oldFile.seek(0, 0)#光标到文件最前面
	print("copy build file to new file \n")
	for sstr in oldFile.readlines():
		newFile.write(sstr)#读取旧的build文件 写入新的build文件
		if sstr[0:4] == "cd -":
			postion = oldFile.tell()
			print("get postion " + str(postion))
			newFile.write("cp output/uni_app_release.bin output/yfc_data_`date +%y%m%d%H%M`.bin \n")
			newFile.write("mkdir -p ../Hummingbird-M-Production-Tool/bin/" + str(outputStr) + "/ \n")
			newFile.write("cp output/*.bin ../Hummingbird-M-Production-Tool/bin/" + str(outputStr) + "/ \n")#复制到烧录软件bin文件夹
			#复制到客户文件夹
			bulidDir = "./"
			bulidDir += outputStr
			newFile.write("cp output/*.bin " + str(bulidDir) + "/ \n")#
			#把编译后的客户文件夹复制到上一级output目录
			newFile.write("cp -r " + str(bulidDir) + " " + OUTPUT_DIR + "/ \n")#
	print("success to write new build.sh \n")



if __name__ == '__main__':
	buildFile = open(BUILD_FILE, mode="r+", newline="\n", encoding='utf-8')
	newBuildFile = open(NEW_BUILD_FILE, mode="w", newline='\n', encoding='utf-8')
	cusJsonFile = open(CUSTOM_JSON_FILE, mode="r", encoding='utf-8')

	try:
		print("load json file\n")
		customJson = json.load(cusJsonFile)
	except Exception as e:
		print('pin_config prase err:'+ e )
		cusJsonFile.close()
		buildFile.close()
		newBuildFile.close()
		#exit

	edit_build(buildFile, newBuildFile, customJson)
	
	cusJsonFile.close()
	buildFile.close()
	newBuildFile.close()
